package client;

import java.io.*;
import java.net.Socket;

public class RequestHandler {
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 12345;

    private Socket socket;
    private BufferedWriter writer;
    private BufferedReader reader;

    public RequestHandler() throws IOException {
        // 初始化Socket和IO流
        socket = new Socket(SERVER_HOST, SERVER_PORT);
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    public void viewContacts() throws IOException {
        sendRequest("VIEW");
    }

    public void addContact(String name, String phone) throws IOException {
        sendRequest("ADD:" + name + ":" + phone);
    }

    public void deleteContact(String name) throws IOException {
        sendRequest("DELETE:" + name);
    }

    public void updateContact(String name, String newPhone) throws IOException {
        sendRequest("UPDATE:" + name + ":" + newPhone);
    }

    private void sendRequest(String request) throws IOException {
        writer.write(request + "\n");
        writer.flush();

        String response = reader.readLine();
        System.out.println("服务器响应: " + response);
    }

    public void close() throws IOException {
        // 关闭连接
        writer.close();
        reader.close();
        socket.close();
    }
}
